<template>
<a-page-header class="demo-page-header" style="border: 1px solid rgb(235, 237, 240)" title="任务制定" sub-title="在此制定任务 以便于在计划中实现拖拽移动">
    <span style="color:cadetblue">在此制定任务 以便于在计划中实现拖拽移动</span>
    <template #tags>
        <a-tag color="blue">Task fumalation</a-tag>
    </template>
</a-page-header>

<div style="margin: 24px;">
    <a-row>
        <a-col :span="16">
            <a-radio-group v-model:value="taskType" @change="handleTaskTypeChange">
                <a-radio-button value="-1">所有任务</a-radio-button>
                <a-radio-button value="0">一次性任务</a-radio-button>
                <a-radio-button value="1">日常任务</a-radio-button>
                <a-radio-button value="2">目标性任务</a-radio-button>
                <a-radio-button value="3">复杂型任务</a-radio-button>
            </a-radio-group>
        </a-col>
        <a-col :span="8">
            <TableHeaderButtonGroup 
            placeholder="请输入任务名称"
            @add="showModal('add',null)" 
            @refresh="handleRefresh"
            @search="handleSearch" />
            <!-- <a-button type="primary" @click="showModal('add')">新增任务</a-button> -->
            <!-- 便捷筛选按钮，还没写逻辑 -->
        </a-col>
    </a-row>

</div>
<a-card>
    <!-- 后期切换成动态加载列 -->
    <a-table :columns="columns" :dataSource="tasks" rowKey="id" :pagination="true">
        <!-- 时代变了，slot已经被淘汰了，我他妈无语死了，难怪一直渲染不出来 -->

       
        <template v-slot:bodyCell="{record, column}">
            <!-- 类型标签 -->
            <template v-if="column.key === 'type'">
                <a-tag color="pink" v-if="record.type===0"> 一次性任务 </a-tag>
                <a-tag color="green" v-if="record.type===1"> 日常性任务 </a-tag>
                <a-tag color="blue" v-if="record.type===2"> 目标性任务 </a-tag>
                <a-tag color="red" v-if="record.type===3"> 复杂型任务 </a-tag>
            </template>

            <!-- 优先级标签 -->
            <template v-if="column.key === 'priority'">
              <!--  -->
                <a-tag color="blue" v-if="record.priority===0"> 低 </a-tag>
                <a-tag color="green" v-if="record.priority===1"> 中 </a-tag>
                <a-tag color="red" v-if="record.priority===2"> 高 </a-tag>
                <a-tag color="gray" v-if="record.priority===3"> 紧急 </a-tag>
            </template>
            <!-- 状态标签 -->
            <template v-if="column.key==='status'">
              <a-tag color="blue" v-if="record.status===0">未完成 </a-tag>
              <a-tag color="green" v-if="record.status===1"> 进行中 </a-tag>
              <a-tag color="red" v-if="record.status===2"> 已开始 </a-tag>
            </template>

            <!-- 目标次数与剩余次数 组合计算并渲染出进度条 -->
            <template v-if="column.key==='completeness'" style="min-width:200px">
                <a-progress  size="small" 
                :percent="((record.targetTime - record.remainTime)/record.targetTime)*100"
                :format="() => `${record.targetTime - record.remainTime}/${record.targetTime}`"
                 />
            </template>
            <!-- 操作列按钮 -->
            <template v-if="column.key === 'action'">
                <a-space size="middle">
                    <a-button type="link" @click="showModal('edit', record)">编辑</a-button>
                    <a-button type="link" danger @click="confirmDelete(record)">删除</a-button>
                </a-space>
            </template>


        </template>

    </a-table>

    <a-modal v-model:open="visible" title="任务操作" @ok="handleOk" @cancel="handleCancel">
        <a-form :model="form" :rules="rules" ref="formRef">
            <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入任务名称' }]">
                <a-input v-model:value="form.name" />
            </a-form-item>
            <a-form-item label="描述" name="description">
                <a-textarea v-model:value="form.description" />
            </a-form-item>
            <a-form-item label="优先级" name="priority" :rules="[{ required: true, message: '请输入优先级' }]">
                <a-select v-model:value="form.priority" :options="priorityOptions" />
            </a-form-item>
            <a-form-item label="状态" name="status" :rules="[{ required: true, message: '请输入状态' }]">
                <a-select v-model:value="form.status" :options="statusOptions" />
            </a-form-item>
            <a-form-item label="类型" name="type" :rules="[{ required: true, message: '请输入类型' }]">
                <a-select v-model:value="form.type" :options="typeOptions" />
            </a-form-item>
            <a-form-item label="开始日期" name="startDay" :rules="[{ required: true, message: '请输入开始日期', type: 'date' }]">
                <a-date-picker  v-model:value="form.startDay" />
            </a-form-item>
            <a-form-item label="结束日期" name="endDay" :rules="[{ required: true, message: '请输入结束日期', type: 'date' }]">
                <a-date-picker  v-model:value="form.endDay" />
            </a-form-item>
            <a-form-item label="颜色" name="color" :rules="[{ required: true, message: '请输入颜色' }]">
                <ColorPicker v-model="form.color" />
            </a-form-item>
        </a-form>
    </a-modal>
</a-card>
</template>

<script setup>
import {
    h,
    ref,
    onMounted,
    reactive,
} from 'vue';
import {
    getAllTaskByUserId,
    getTaskByUserIdByName,
    getTaskByUserIdByType
} from '../api/task';
import TableHeaderButtonGroup from '../components/TableHeaderButtonGroup.vue';
import dayjs from 'dayjs';
import ColorPicker from '../components/ColorPicker.vue';
import { createTask,updateTask } from '../api/task';

const tasks = ref([]);
//用ref包装的对象，要使用form.value.xxx来访问
//用reactive包装的对象，直接使用form.xxx来访问
const form = ref({
    id: null,
    name: '',
    description: '',
    priority: null,
    status: null,
    type: null,
    startDay: null,
    endDay: null,
    targetTime: null,
    remainTime: null,
    color: ''
});
const visible = ref(false);
const formRef = ref(null);

const columns = [{
        title: 'ID',
        dataIndex: 'id',
        key: 'id'
    },
    {
        title: '名称',
        dataIndex: 'name',
        key: 'name'
    },
    {
        title: '描述',
        dataIndex: 'description',
        key: 'description'
    },
    {
        title: '优先级',
        dataIndex: 'priority',
        key: 'priority'
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status'
    },
    {
        title: '类型',
        dataIndex: 'type',
        key: 'type'
    },
    {
        title: '开始日期',
        dataIndex: 'startDay',
        key: 'startDay'
    },
    {
        title: '结束日期',
        dataIndex: 'endDay',
        key: 'endDay'
    },
    {
        title: '颜色',
        dataIndex: 'color',
        key: 'color'
    },
    {
        title:'完成度',
        dataIndex:'completeness',
        key:'completeness'
    },
    {
        title:'持续时间',
        dataIndex:'duration',
        key:'duration'
    },
    {
        title: '操作',
        key: 'action'
    }
];

//下拉框选项
const typeOptions = [{
        label: '一次性任务',
        value: 0
    },
    {
        label: '日常任务',
        value: 1
    },
    {
        label: '目标性任务',
        value: 2
    },
    {
        label: '复杂型任务',
        value: 3
    }
];
const priorityOptions = [{
        label: '低',
        value: 0
    },
    {
        label: '中',
        value: 1
    },
    {
        label: '高',
        value: 2
    },
    {
        label: '紧急',
        value: 3
    }
];
const statusOptions = [{
        label: '未完成',
        value: 0
    },
    {
        label: '进行中',
        value: 1
    },
    {
        label: '已开始',
        value: 2
    }
];

const rules = {
    name: [{
        required: true,
        message: '请输入任务名称',
        trigger: 'blur'
    }],
    priority: [{
        required: true,
        message: '请选择优先级',
        trigger: 'change'
    }],
    status: [{
        required: true,
        message: '请选择状态',
        trigger: 'change'
    }],
    type: [{
        required: true,
        message: '请选择类型',
        trigger: 'change'
    }],
    startDay: [{
        required: true,
        message: '请选择开始日期',
        trigger: 'change'
    }],
    endDay: [{
        required: true,
        message: '请选择结束日期',
        trigger: 'change'
    }],
    color: [{
        required: true,
        message: '请输入颜色',
        trigger: 'blur'
    }]
};
//清空模态框表单，根据按钮类型显示模态框
function showModal(type, record) {  
    if (type === 'add') {
        // 清空表单
        form.value.id = null;
        form.value.name = '';
        form.value.description = '';
        form.value.priority = null;
        form.value.status = null;
        form.value.type = null;
        form.value.startDay = null;
        form.value.endDay = null;
        form.value.color = '#ffffff';
    }else if(type==='edit'){
        //编辑任务
        form.value.id = record.id || null;
        form.value.name = record.name || '';
        form.value.description = record.description || '';
        //数字型的数据不能简单地用||null来判断是否为空
        //因为0也会被判断为空，所以要用!==undefined && !==null来判断是否为空
        form.value.priority = record.priority !== undefined && record.priority !== null ? record.priority : null;
        form.value.status = record.status !== undefined && record.status !== null ? record.status : null;
        form.value.type = record.type !== undefined && record.type !== null ? record.type : null;
        form.value.startDay = record.startDay ? dayjs(record.startDay) : null;
        form.value.endDay = record.endDay ? dayjs(record.endDay)  : null;
        form.value.color = record.color || '';
        form.value.targetTime = record.targetTime || null;
        form.value.remainTime = record.remainTime || null;
    }
    //显示表单界面
    visible.value = true;
}

function handleOk() {

    //坑点，验证是个异步操作，form就算双向绑定了，也会因为时差问题呈现出旧的数据，这都可以写个底层研究的博客了
    formRef.value.validateFields().then(
        (values) => { // 重点：使用 validateFields 返回的 values 参数
        if (form.value.id) {
        // 合并 id 到最新数据中，确保数据完整性
        const updatedTaskData = { ...values, id: form.value.id, targetTime:form.value.targetTime, remainTime:form.value.remainTime};
        // 将日期对象转换为字符串格式
        updatedTaskData.startDay = updatedTaskData.startDay ? updatedTaskData.startDay.format('YYYY-MM-DD') : null;
        updatedTaskData.endDay = updatedTaskData.endDay ? updatedTaskData.endDay.format('YYYY-MM-DD') : null;
        updateTask(updatedTaskData).then(response => {
            const index = tasks.value.findIndex(task => task.id === form.value.id);
            if (index > -1) {
            // 直接使用最新数据 updatedTask 更新本地状态
            tasks.value[index] = updatedTaskData;
            }
            console.log("更新后的本地数据:", tasks.value[index]);
        });
        } else {
        createTask(values).then(response => {
            handleRefresh();
        });
}
    
    visible.value = false;
    formRef.value.resetFields();
  })
  .catch(info => {
    console.log('验证失败:', info);
  });
    
    
}
//处理刷新
function handleRefresh(){
    handleTaskTypeChange();

}

function handleSearch(value) {
    getTaskByUserIdByName(value).then(response => {
        tasks.value = response.data.data;
    })
    console.log('搜索关键字:', value);
}
function handleCancel() {
    visible.value = false;
    formRef.value.resetFields();
}

function confirmDelete(record) {
    const index = tasks.findIndex(task => task.id === record.id);
    if (index > -1) {
        tasks.splice(index, 1);
    }
}

//初始筛选条件 为所有任务
const taskType=ref(-1);

function handleTaskTypeChange(){
    if(taskType.value==-1){
        console.log('所有任务');
        getAllTaskByUserId().then(response => {
            tasks.value = response.data;
        })
    }else{
        getTaskByUserIdByType(taskType.value).then(response => {
            tasks.value = response.data;
        })
    }
}
onMounted(() => {
    getAllTaskByUserId().then(response => {
        tasks.value = response.data;
    })
})
</script>

<style scoped>
/* 添加一些基本的样式 */
.ant-btn {
    margin-right: 8px;
}

.ant-card {
    margin: 24px;
}

</style>
